<template>
    <div class="top_bar">
        <div class="logo"><img src="https://bu.dusays.com/2024/09/28/66f7782a0e175.png" alt=""></div>
        <div class="search">
            <el-input v-model="search_input" placeholder="热门商品" :prefix-icon="Search" />
            <div class="search_btn">
                <v-btn class="search_btn_v" :ripple="false" height="5vh" min-width="15vh">
                    搜索
                </v-btn>
            </div>
        </div>
    </div>
    <div class="body">
        <div style="display: flex; justify-content: center; align-items: center; width: 100%; height: 100%;">
            <div class="card" style="width: 90%; height: 100%; padding: 30px; box-sizing: border-box;">
                <el-form :model="data.user" label-width="100px" style="padding-right: 50px; height: 50%;">
                    <div style="margin: 20px 0; text-align: center">
                        <el-upload :show-file-list="false" class="avatar-uploader" :action="uploadUrl"
                            :on-success="handleFileUpload">
                            <img v-if="data.user.avatar" :src="data.user.avatar" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </div>
                    <el-form-item label="账号">
                        <el-input disabled v-model="data.user.username" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="名称">
                        <el-input v-model="data.user.name" autocomplete="off" />
                    </el-form-item>
                    <div style="text-align: center">
                        <el-button type="primary" @click="save">保存</el-button>
                        <el-button @click="logout">退出登录</el-button>
                    </div>
                </el-form>
                <div style="margin-bottom: 2vh;">
                    <h2>收货地址</h2>
                </div>
                <div style="margin-bottom: 2vh;"><el-button @click="handleAddAddress">新增地址</el-button></div>
                <div class="Address_box">
                    <div class="address_card" v-for="item in otherAddresses">
                        <div class="address_header">
                            收货人姓名：<span class="name">{{ item.recipientName }}</span>
                        </div>
                        <div class="address_field">
                            手机号：<span class="phone">{{ item.phoneNumber }}</span>
                        </div>
                        <div class="address_field">
                            省份：<span class="province">{{ item.province }}</span>
                        </div>
                        <div class="address_field">
                            区域：<span class="area">{{ item.city }}</span>
                        </div>
                        <div class="address_field">
                            街道：<span class="street">{{ item.district }}</span>
                        </div>
                        <div class="address_field">
                            详细地址：<span class="detail">{{ item.detailAddress }}</span>
                        </div>
                    </div>
                    <el-dialog title="增加收货地址" width="40%" v-model="data.formVisible" :close-on-click-modal="false"
                        destroy-on-close>
                        <el-form :model="data.form" label-width="100px" style="padding-right: 50px">

                            <el-form-item label="收货人姓名" prop="recipientName">
                                <el-input v-model="data.form.recipientName" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="收货人电话" prop="phoneNumber">
                                <el-input v-model="data.form.phoneNumber" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="省份" prop="province">
                                <el-input v-model="data.form.province" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="市区" prop="city">
                                <el-input v-model="data.form.city" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="街道" prop="district">
                                <el-input v-model="data.form.district" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="详细地址" prop="detailAddress">
                                <el-input v-model="data.form.detailAddress" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="data.formVisible = false">取 消</el-button>
                                <el-button type="primary" @click="address">新增</el-button>
                            </span>
                        </template>
                    </el-dialog>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { Calendar, Search } from '@element-plus/icons-vue';
import { reactive } from "vue"
import request from '../../utils/request';
import { ElMessage } from "element-plus";
import { ref } from 'vue';
import { onMounted } from "vue";
import router from "@/router";

// 文件上传的接口地址
//const uploadUrl = 'http://localhost:9090/files/upload'
const uploadUrl = 'https://www.chessunyan.asia:9090/files/upload'

const data = reactive({
    user: JSON.parse(localStorage.getItem('system-user') || '{}'),
})

const handleFileUpload = (file) => {
    data.user.avatar = file.data
}

const handleAddAddress = () => {
    data.form = {}
    data.formVisible = true
}

const getUserInfo = () => {
    const uid = sessionStorage.getItem('uid');
    if (uid) {
        const uidObj = JSON.parse(uid);
        request.get('/api/user/GetUserInfo', {
            params: {
                uid: uidObj
            }
        }).then(res => {
            data.user = res.data;
        }).catch(error => {
            console.error("请求失败", error);
        })
    } else {
        console.log("未登录");
        data.user.value.avatar = "https://bu.dusays.com/2024/12/28/677018da4485e.png";
    }
}

const logout = () => {
    ElMessage.success('退出成功')
    localStorage.removeItem('system-user')
    router.push('/login')
}

const emit = defineEmits(["updateUser"])
// 把当前修改的用户信息存储到后台数据库
const save = () => {
    console.log(data.user);
    request.put('/api/user/updateMySelf',data.user).then(res=>{
        if (res.code === '200') {
                ElMessage.success('更新成功')
            }
    })

    if (data.user.role === 'ADMIN') {
        request.put('/admin/update', data.user).then(res => {
            if (res.code === '200') {
                ElMessage.success('更新成功')
                //把更新后的用户信息存储到缓存
                localStorage.setItem('system-user', JSON.stringify(data.user))
                emit('updateUser')
            } else {
                ElMessage.error(res.msg)
            }
        })
    }
}

const otherAddresses = ref([]);

const load = () => {
    request.get(`/api/user/selectUserAddressAll/${JSON.parse(sessionStorage.getItem('uid'))}`).then(res => {
        otherAddresses.value = res.data;
        console.log(otherAddresses.value);
    }).catch(error => {
        console.error('请求失败:', error);
    })
}


onMounted(async() => {
    await getUserInfo();
    await load();
})


const address = () => {
    data.form.uid = data.user.uid;
    request.post("/api/user/AddUserAddress", data.form).then(res => {
        if (res.code === '200') {
            load();
            ElMessage.success("添加成功");
            data.formVisible = false
        }
        else {
            ElMessage.error("添加失败")
        }
    })
}

</script>
<style scoped>
.body {
    height: auto;
    height: 80vh;
}

.top_bar {
    width: 100%;
    height: 10vh;
    /* background-color: wheat; */
    display: flex;
}

.top_bar img {
    width: 20vh;
    height: auto;
    margin-left: 15vh;
}

.top_bar .search {
    width: 100vh;
    margin: auto;
    margin-left: 10vh;
    display: flex;
}

.search .search_btn_v {
    background-color: greenyellow;
    font-size: 2.5vh;
}


.avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}

.Address_box {
    display: flex;
    gap: 2vh;
}

.address_card {
    width: 20vh;
    background-color: #f9f9f9;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 10px;
}

.address_header {
    font-size: 1vh;
    font-weight: bold;
    margin-bottom: 10px;
}

.address_field {
    font-size: 1vh;
    margin-bottom: 5px;
}

.address_field span {
    font-size: 1vh;
    font-weight: bold;
}
</style>